<template>
  <div style="width: 800px; margin: 0 auto">
    <h1>管理员登录</h1>
    <div>
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="登录账号" prop="userName">
          <el-input v-model="ruleForm.userName" />
        </el-form-item>
        <el-form-item label="登录密码" prop="userPass">
          <el-input v-model="ruleForm.userPass" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            登录
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { login } from "../api/api";
import { useRouter } from "vue-router";

interface RuleForm {
  userName: string;
  userPass: string;
}

const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  userName: "",
  userPass: "",
});

const rules = reactive<FormRules<RuleForm>>({
  userName: [
    { required: true, message: "请输入登录账号", trigger: "blur" },
    { min: 6, message: "登录账号长度最小6个字符", trigger: "blur" },
  ],
  userPass: [
    { required: true, message: "请输入登录密码", trigger: "blur" },
    {
      pattern: /^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{6,}$/,
      message: "密码不能小于6位,并且包含字母和数字",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      login(ruleForm).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("登陆成功");
          let user = res.data.data;
          let token = user.token;
          sessionStorage.setItem("token", token);
          sessionStorage.setItem("user", JSON.stringify(user));
          router.push("/home");
        } else {
          ElMessage.error(res.data.message);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
